<template>
  <div>
    <el-form ref="form" label-width="80px" :model="spu">
      <el-form-item label="SPU名称">
        <el-input placeholder="spu名称" v-model="spu.spuName"></el-input>
      </el-form-item>
      <el-form-item label="品牌">
        <el-select placeholder="请选择品牌" v-model="spu.tmId">
          <el-option
            :label="tm.tmName"
            :value="tm.id"
            v-for="(tm, index) in tradeMarkList"
            :key="tm.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述">
        <el-input
          type="textarea"
          rows="4"
          placeholder="描述"
          v-model="spu.description"
        ></el-input>
      </el-form-item>
      <el-form-item label="SPU照片">
        <el-upload
          action="/dev-api/admin/product/fileUpload"
          list-type="picture-card"
          :file-list="spuImageList"
          :on-success="handlerSuccess"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-select
          :placeholder="`还有${unSelectSaleAttr.length}个未选择`"
          v-model="attrIdAndAttrName"
        >
          <el-option
            :label="unselect.name"
            :value="`${unselect.id}:${unselect.name}`"
            v-for="(unselect, index) in unSelectSaleAttr"
            :key="unselect.id"
          ></el-option>
        </el-select>
        <el-button
          type="primary"
          icon="el-icon-plus"
          :disabled="!attrIdAndAttrName"
          @click="addSaleAttr"
          >添加销售属性</el-button
        >
        <!-- 展示的是当前spu属于自己的销售属性 -->
        <el-table style="width: 100%" border :data="spu.spuSaleAttrList">
          <el-table-column
            type="index"
            label="序号"
            width="80px"
            align="center"
          >
          </el-table-column>
          <el-table-column prop="saleAttrName" label="属性名" width="width">
          </el-table-column>
          <el-table-column prop="prop" label="属性值名称列表" width="width">
            <template slot-scope="{ row, $index }">
              <el-tag
                :key="tag.id"
                v-for="(tag, index) in row.spuSaleAttrValueList"
                closable
                :disable-transitions="false"
                @close="row.spuSaleAttrValueList.splice(index, 1)"
              >
                {{ tag.saleAttrValueName }}
              </el-tag>
              <!-- @keyup.enter.native="handleInputConfirm" -->
              <el-input
                class="input-new-tag"
                v-if="row.inputVisible"
                v-model="row.inputValue"
                ref="saveTagInput"
                size="small"
                @blur="handleInputConfirm(row)"
              >
              </el-input>
              <el-button
                v-else
                class="button-new-tag"
                size="small"
                @click="addSaleAttrValue(row)"
                >添加</el-button
              >
            </template>
          </el-table-column>
          <el-table-column prop="prop" label="操作" width="width">
            <template slot-scope="{ row, $index }">
              <el-button
                type="danger"
                size="mini"
                icon="el-icon-delete"
                @click="spu.spuSaleAttrList.splice($index, 1)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addOrUpdateSpu">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
 
<script>
import { run } from "runjs";
export default {
  name: "SpuForm",
  data() {
    return {
      dialogImageUrl: "",
      dialogVisible: false,
      //存储SPU信息属性
      spu: {
        category3Id: 0,
        // 描述
        description: "",
        // spu名称
        spuName: "",
        // 品牌的id
        tmId: "",
        // 收集spu图片信息
        spuImageList: [
          {
            // id: 0,
            // imgName: "string",
            // imgUrl: "string",
            // spuId: 0,
          },
        ],
        //平台属性与属性值收集
        spuSaleAttrList: [
          // {
          //   baseSaleAttrId: 0,
          //   id: 0,
          //   saleAttrName: "string",
          //   spuId: 0,
          //   spuSaleAttrValueList: [
          //     {
          //       baseSaleAttrId: 0,
          //       id: 0,
          //       isChecked: "string",
          //       saleAttrName: "string",
          //       saleAttrValueName: "string",
          //       spuId: 0,
          //     },
          //   ],
          // },
        ],
        // tag标签
        dynamicTags: [],
        inputVisible: false,
        inputValue: "",
      },
      tradeMarkList: [], //存储品牌信息
      spuImageList: [], //存储spu图片数据
      saleAttrList: [], //存储销售属性的数据
      attrIdAndAttrName: "", //收集选择的id
    };
  },
  methods: {
    // 上传照片墙
    // 照片墙再删除图片的时候需要收集数据
    handleRemove(file, fileList) {
      // file:代表删除的图片
      // fileList：删除图片后剩余的图片
      // console.log(file, fileList);
      // 收集照片墙数据
      this.spuImageList = fileList;
    },
    handlePictureCardPreview(file) {
      // 将图片地址赋值给这个属性
      this.dialogImageUrl = file.url;
      //对话框显示
      this.dialogVisible = true;
    },
    // 照片墙图片上传成功回调
    handlerSuccess(response, fiel, fileList) {
      this.spuImageList = fileList;
    },
    //初始化SpuForm数据
    async initSpuDate(spu) {
      // console.log(spu);
      // 获取SPU信息的数据
      let spuResult = await this.$API.spu.reqSpu(spu.id);
      if (spuResult.code == 200) {
        // 在修改spu的时候，需要向服务器发请求，把服务器返回的数据（对象）赋值给spu属性
        this.spu = spuResult.data;
      }
      // 获取品牌的数据
      let tradeMarkResult = await this.$API.spu.reqTradeMarkList();
      if (tradeMarkResult.code == 200) {
        this.tradeMarkList = tradeMarkResult.data;
      }
      // 获取SPU图片的数据
      let spuImageResult = await this.$API.spu.reqSpuImageList(spu.id);
      if (spuImageResult.code == 200) {
        let listArry = spuImageResult.data;
        //由于照片墙显示图片需要的数据需要数组，数组里面的元素需要name和url
        // 需要把服务器范湖的数据进行修改
        listArry.forEach((item) => {
          item.name = item.imgName;
          item.url = item.imgUrl;
        });
        // 整理好的数据赋值
        this.spuImageList = listArry;
      }
      // 获取平台全部的销售属性
      let saleResult = await this.$API.spu.reqBaseSaleAttrList();
      if (saleResult.code == 200) {
        this.saleAttrList = saleResult.data;
      }
    },
    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.dynamicTags.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = "";
    },
    // 添加新的销售属性
    addSaleAttr() {
      //已经收集需要添加的销售属性
      const [baseSaleAttrId, saleAttrName] = this.attrIdAndAttrName.split(":");
      // 向SPU对象中的spuSaleAttrList属性添加新的销售属性
      let newSaleAttr = {
        baseSaleAttrId,
        saleAttrName,
        spuSaleAttrValueList: [],
      };
      // 添加新的销售属性
      this.spu.spuSaleAttrList.push(newSaleAttr);
      // 清空数据
      this.attrIdAndAttrName = "";
    },
    // 添加按钮的回调
    addSaleAttrValue(row) {
      //挂载在校生属性身上的想原始数据inputVisible，控制button和input的切换
      this.$set(row, "inputVisible", true);
      // 通过响应式数据inputValue字段手机新增的销售数据值
      this.$set(row, "inputValue", "");
    },
    // el-iinput失去焦点的时间
    handleInputConfirm(row) {
      // 结构出销售属性当中收集数据
      const { baseSaleAttrId, inputValue } = row;
      // 判断是否为空
      if (inputValue.trim() == "") {
        this.$message("属性值不能为空");
        return;
      }
      // 属性值不能重复
      let result = row.spuSaleAttrValueList.every(
        (item) => item.saleAttrValueName != inputValue
      );
      if (result) {
        let newSaleAttrValue = {
          baseSaleAttrId,
          saleAttrValueName: inputValue,
        };
        // 新增
        row.spuSaleAttrValueList.push(newSaleAttrValue);
      } else {
        return this.$message("属性值不能重复！");
      }
      // 修改inputVisible为false，就不显示button了
      row.inputVisible = false;
      row.inputValue = "";
    },
    // 保存按钮的回调
    async addOrUpdateSpu() {
      // 整理参数--照片墙数据
      this.spu.spuImageList = this.spuImageList.map((item) => {
        return {
          imageName: item.name,
          imageUrl: (item.response && item.response.data) || item.url,
        };
      });
      // 发请求
      let result = await this.$API.spu.reqAddSpuOrUpdateSpu(this.spu);
      // console.log(result);
      if (result.code == 200) {
        // 修改成功
        this.$message({ type: "success", message: "修改成功" });
        // 通知父组件回到secne==0处
        this.$emit("changeScene", {
          scene: 0,
          flag: this.spu.id ? "修改" : "添加",
        });
      }
    },
    // 点击添加spu按钮请求的函数
    async addSpuData(category3Id) {
      // 添加spu时收集三级分类id
      this.spu.category3Id = category3Id;
      // 获取品牌的数据
      let tradeMarkResult = await this.$API.spu.reqTradeMarkList();
      if (tradeMarkResult.code == 200) {
        this.tradeMarkList = tradeMarkResult.data;
      }
      // 获取平台全部的销售属性
      let saleResult = await this.$API.spu.reqBaseSaleAttrList();
      if (saleResult.code == 200) {
        this.saleAttrList = saleResult.data;
      }
    },
    // 取消按钮
    cancel() {
      // 取消按钮的回调，通知父亲切换场景为
      this.$emit("changeScene", { scene: 0, flag: "" });
      //清除数据
      // Object.assign:ES6中新增方法，可以合并对象
      Object.assign(this._data, this.$options.data());
    },
  },
  computed: {
    //计算出还未选择的销售属性
    unSelectSaleAttr() {
      // 整个平台一个三个:尺寸、颜色、版本
      // 当SPU拥有自己的销售属性SPU.spuSaleAttrList ----颜色
      // 数组的过滤
      let result = this.saleAttrList.filter((item) => {
        return this.spu.spuSaleAttrList.every((item1) => {
          return item.name != item1.saleAttrName;
        });
      });
      return result;
    },
  },
};
</script>
 
<style lang='css'>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>